import os
import sys
import random
import shutil

from PIL import Image
import win32api
import win32con


# 入参处理
argv = sys.argv
if len(argv) <= 1:
    print("请输入要筛选的图片文件夹路径")
    exit()
if len(argv) >= 2:
    image_path = argv[1]
    if not os.path.exists(image_path):
        print("要筛选的图片文件夹路径不存在")
        exit()
if len(argv) >= 3:
    save_path = argv[2]
else:
    save_path = os.path.join(os.path.split(os.path.abspath(__file__))[0],
                             "imageFilterOutput")
if not os.path.exists(save_path):
    os.mkdir(save_path)


def image_filter(path):
    for name in os.listdir(path):
        path_name = os.path.join(path, name)
        if os.path.isdir(path_name):
            image_filter(path_name)
        elif name.lower().endswith((".png", ".jpg", ".jpeg", ".bmp")):
            image_size = Image.open(path_name).size
            image_width, image_height = image_size
            screen_width = win32api.GetSystemMetrics(win32con.SM_CXSCREEN)
            screen_height = win32api.GetSystemMetrics(win32con.SM_CYSCREEN)
            if (image_width > image_height >= screen_height and
                    image_width >= screen_width):
                if os.path.exists(os.path.join(save_path, name)):
                    new_path_name = os.path.join(
                        path, str(random.randint(1, 10000)) + name)
                    os.rename(path_name, new_path_name)
                    path_name = new_path_name
                shutil.move(path_name, save_path)


image_filter(image_path)
